//
//  TicketOrderView.m
//  LocalTravel
//
//  Created by zheng ji on 14-3-22.
//  Copyright (c) 2014年 jxw. All rights reserved.
//
#define NUMBERS @"0123456789.\n"
#import "TicketOrderView.h"

@interface TicketOrderView(){
    CKCalendarView* _calendar;
    double _tcPrice;
    double _price;
    NSString* _policyId;
    BOOL _needIdCard;// 是否需要身份证号码
    int _maxT; //最大预订张数
    int _minT;//最少预订张数
    int _beforeDays;//提前天数
    CGRect _submitOrderFrame;
}
@end

@implementation TicketOrderView
- (IBAction)btnSubmitOrder:(UIButton *)sender {
    
    NSString* sceneryId=[self.dictScenery objectForKey:@"sceneryId"];
    NSString* bMan=[self.lblName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString* bMobile=[self.lblPhoneNumber.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString* tName=bMan;
    NSString* tMobile=bMobile;
    //NSString* policyId=_policyId;
    NSString* tickets=[self.textFieldCount.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString* travelDate=[self.textFieldDate.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString* idCard=[self.lblIdCard.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if(travelDate==nil ||[travelDate  isEqualToString:@""]){
        self.lblResultTip.text=@"请选择游玩日期！";
        return ;
    }
    if(bMan==nil || [bMan  isEqualToString:@""]){
        self.lblResultTip.text=@"请输入取票人姓名！";
        return ;
    }
    if(bMobile==nil ||[bMobile  isEqualToString:@""]){
        self.lblResultTip.text=@"请输入手机号码！";
        return ;
    }else if(bMobile.length!=11){
        
            self.lblResultTip.text=@"请输入正确的手机号码！";
            return ;
      

    }else{
        NSString* strM = [bMobile stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
        if(strM.length != 0)
        {
            self.lblResultTip.text=@"请输入正确的手机号码！";
            return ;
        }
         
    }
    if(tickets==nil ||[tickets  isEqualToString:@""]){
        self.lblResultTip.text=@"请输入预订张数！";
        return ;
    }
  
    if(_needIdCard ){
        if( idCard==nil ||[idCard  isEqualToString:@""]){
           self.lblResultTip.text=@"请输入身份证号码！";
             return ;
        }else if(idCard.length!=18){
            self.lblResultTip.text=@"请输入正确的18位身份证号码！";
             return ;
        }
       
    }
    
    if(_maxT >0){
        if([tickets intValue]>_maxT){
            self.lblResultTip.text=[NSString stringWithFormat:@"最大预订张数：%d",_maxT];
        }
    }
    if(_minT >0){
        if([tickets intValue]<_minT){
            self.lblResultTip.text=[NSString stringWithFormat:@"最少预订张数：%d",_minT];
        }
    }
    
    if(_beforeDays>0){
        
        NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
        fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
        fmt.dateFormat = @"yyyy-MM-dd";
        
        NSDate* selectedDate=[fmt dateFromString:travelDate];
        NSDate *now=[[NSDate alloc]init];
        
         now= [now dateByAddingTimeInterval:(24*60*60*_beforeDays)];
        
        if([selectedDate compare:now]==NSOrderedAscending){
            self.lblResultTip.text=[NSString stringWithFormat:@"须提前：%d天预订",_beforeDays];
            return;
        }
        
    }
    
    NSDictionary* dictRequest=[NSDictionary dictionaryWithObjectsAndKeys:sceneryId,@"sceneryId", bMan,@"bMan",bMobile,@"bMobile",tName,@"tName",tMobile,@"tMobile",_policyId,@"policyId",tickets,@"tickets",travelDate,@"travelDate",idCard,@"idCard",nil];
    
    [self.delegate submitOrder:dictRequest];
   // [self calButtonOrderFrame:_needIdCard];
    //[self.btnSubmitOrder setFrame:_submitOrderFrame];
    
}

- (IBAction)stepperValueChanged:(UIStepper *)sender {
    self.textFieldCount.text=[NSString stringWithFormat:@"%.f",sender.value];
    self.lblCount.text=[NSString stringWithFormat:@"X%.f",sender.value];
    double count=[self.textFieldCount.text doubleValue];
    self.lblPriceTotal.text=[NSString stringWithFormat:@"总额 %.2f",_tcPrice*count];
    self.lblJieYue.text=[NSString stringWithFormat:@"节约：%.2f",count *(_price - _tcPrice)];
    
    
}
- (void)calendar:(CKCalendarView *)calendar didSelectDate:(NSDate *)date{
     NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
      fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
      fmt.dateFormat = @"yyyy-MM-dd";
     self.textFieldDate.text = [fmt stringFromDate:date];
    
    _calendar.hidden=YES;
    [self.textFieldDate resignFirstResponder];
    [self.btnSubmitOrder setFrame:_submitOrderFrame];
    
}

- (IBAction)travelDateTouchDown:(UITextField *)sender {
    
    if(_calendar==nil){
        _calendar = [[CKCalendarView alloc] initWithStartDay:startMonday];
        _calendar.frame = CGRectMake(sender.frame.origin.x, sender.frame.origin.y+sender.frame.size.height , 300, 470);
        _calendar.delegate=self;
        [self addSubview:_calendar];
    }else{
        _calendar.hidden=NO;
    }

}
//- (IBAction)travelDateSelect:(UITextField*)sender {
    
  // }

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"TicketOrderView" owner:self options: nil];
        
        // 如果路径不存在，return nil
        
        if(arrayOfViews.count < 1){return nil;}
        
        // 如果xib中view不属于TicketTableCell类，return nil
        
        if(![[arrayOfViews objectAtIndex:0] isKindOfClass:[TicketOrderView class]]){
            
            return nil;
            
        }
        
        self = [arrayOfViews objectAtIndex:0];
        self.frame=frame;
    }
    self.lblResultTip.text=@"";
    self.textFieldCount.delegate=self;
    self.lblPhoneNumber.delegate=self;
    if(IsIOS7){
       self.btnSubmitOrder.backgroundColor=[UIColor orangeColor];
        self.btnSubmitOrder.titleLabel.textColor=[UIColor whiteColor];
    }else{
        self.btnSubmitOrder.titleLabel.textColor=[UIColor orangeColor];
        //self.btnSubmitOrder.titleLabel.backgroundColor=[UIColor blueColor];
    }
    _maxT=0;
    _minT=0;
    _beforeDays=0;
    _needIdCard=NO;
   // self.btnSubmitOrder.tintColor=[UIColor whiteColor];
    //self.backgroundColor=RGB(211,211,211);
    return self;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{
    return YES;
    /*
    NSCharacterSet *cs;
    
   cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
    
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    
    BOOL basicTest = [string isEqualToString:filtered];
    
    if(!basicTest)
        
    {
        
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示"
                              
                                                        message:@"请输入数字"
                              
                                                       delegate:nil
                              
                                              cancelButtonTitle:@"确定"
                              
                                              otherButtonTitles:nil];
        
        
        
        [alert show];
        
        return NO;
        
    }
    
    else if (textField.text.length>10)
        
    {
        
        
        
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示"
                              
                                                        message:@"输入格式错误"
                              
                                                       delegate:nil
                              
                                              cancelButtonTitle:@"确定"
                              
                                              otherButtonTitles:nil];
        
        
        
        [alert show];
        
        return NO;
        
    }
    
    
    
    return YES;
     */
    
}
-(void)showTicketDetail:(NSDictionary*)dict  otherDict:(NSMutableDictionary*)otherDict{
    if(dict ==nil) return ;
    self.lblResultTip.text=@"";
    self.lblTicketName.text=[dict objectForKey:@"policyName"];
    _policyId=[dict objectForKey:@"policyId"];
    
    self.lblDescription.text=[NSString stringWithFormat:@"说明：\r\n\r\n%@ \r\n \r\n取票地点：\r\n\r\n%@",[dict objectForKey:@"remark"],[dict objectForKey:@"gMode"]];
    self.lblPrice.text=[NSString stringWithFormat:@"¥：%@",[dict objectForKey:@"tcPrice"] ];
    _tcPrice=[[dict objectForKey:@"tcPrice"] doubleValue ];
    _price=[[dict objectForKey:@"price"] doubleValue ];
    
    
    
    NSString* strMinT=[dict objectForKey:@"minT"];
    NSString* strMaxT=[dict objectForKey:@"maxT"];
    
    if(strMaxT !=nil && ![strMaxT isEqualToString:@""]){
        _maxT=[strMaxT intValue];
    }
    if(strMinT !=nil && ![strMinT isEqualToString:@""]){
        _minT=[strMinT intValue];
    }
    if(_minT==0) _minT=1;
    
    self.textFieldCount.text=[NSString stringWithFormat:@"%d",_minT];
    
    self.lblCount.text=[NSString stringWithFormat:@"X%@",self.textFieldCount.text];
    
    double count=[self.textFieldCount.text doubleValue];
    
    
    self.lblPriceTotal.text=[NSString stringWithFormat:@"总额：%.2f",count * _tcPrice];
    self.lblJieYue.text=[NSString stringWithFormat:@"节约：%.2f",count *(_price - _tcPrice)];
    NSString* date=[otherDict objectForKey:@"day"];
    NSString* time=[otherDict objectForKey:@"time"];
    
    NSMutableString* buffer=[[NSMutableString alloc]init];
    if(date !=nil && ![date isEqualToString:@""]){
        [buffer appendFormat:@"须提前%@天",date];
        _beforeDays=[date intValue];
    }
    if(time !=nil && ![time isEqualToString:@""]){
        [buffer appendFormat:@"[%@前]",time];
    }
    
    self.lblTips.text=[NSString stringWithFormat:@"温馨提示：本票型%@ 预订张数限制%@-%@张。订单提交成功后，您将收到同程网的订单确认短信。凭此短信直接到同程指定的售票窗口取票。",buffer,[dict objectForKey:@"minT"],[dict objectForKey:@"maxT"]];
   // NSString* useCard=[dict objectForKey:@"useCard"];
    //if(useCard !=nil && [useCard isEqualToString:@"1"]){
    if(_needIdCard){
        //需要二代身份证
        self.lblIdCard.hidden=NO;
        self.lblShenFengZheng.hidden=NO;
        _needIdCard=YES;
        self.cardBackgroudView.hidden=NO;
      
        //self.lblIdCard.placeholder=@"用于景点取票";
    }else{
        self.lblIdCard.hidden=YES;
        self.lblShenFengZheng.hidden=YES;
        _needIdCard=NO;
        self.cardBackgroudView.hidden=YES;
       
    }
    
    [self.btnSubmitOrder setFrame:_submitOrderFrame];
    
    
}

-(void)calButtonOrderFrame:(BOOL)needCard{
    _needIdCard=needCard;
    if(needCard){
        _submitOrderFrame=self.btnSubmitOrder.frame;
    }else{
        
         _submitOrderFrame=self.btnSubmitOrder.frame;
        _submitOrderFrame.origin.y=_submitOrderFrame.origin.y-55;
        [self.btnSubmitOrder setFrame:_submitOrderFrame];

        
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
